package services

import (
	"fmt"

	"github.com/sirupsen/logrus"
)

/*
1字节	字段号(固定1)
1字节	寄存器编号高字节
1字节	寄存器编号高字节
1字节	寄存器个数N字节
1字节	寄存器数据1
1字节	寄存器数据2
1字节	寄存器数据3
1字节	寄存器数据4
*/
type DeviceData struct {
	FieldNumber  uint8
	RegisterHigh uint8
	RegisterLow  uint8
	RegisterNum  uint8
	RegisterData []uint8
	Mac          string
}

// 初始化设备数据
func (d *DeviceData) InitDeviceData(payload []byte, mac string) error {
	if len(payload) < 5 {
		// 数据长度不足
		return fmt.Errorf("payload:%v data length is invalid", payload)
	}
	// 校验数据个数是否正确
	if int(payload[3]) != len(payload)-4 {
		logrus.Warn("payload:", payload)
		// 数据个数不正确
		return fmt.Errorf("payload:%v data number is invalid", payload)
	}
	d.FieldNumber = payload[0]
	d.RegisterHigh = payload[1]
	d.RegisterLow = payload[2]
	d.RegisterNum = payload[3]
	d.RegisterData = payload[4:]
	d.Mac = mac
	return nil
}

// 根据寄存器编号获取报文类型
func (d *DeviceData) GetPayloadType() string {
	// 判断寄存器编号低字节是否在map中
	if t, ok := PayloadTypeMap[d.RegisterLow]; !ok {
		return "UNKNOWN"
	} else {
		return t
	}
}

// 发送数据到平台
func (d *DeviceData) SendDataToPlatform() error {
	// 根据寄存器编号获取报文类型
	payloadType := d.GetPayloadType()
	logrus.Info("payloadType:", payloadType)
	switch payloadType {
	case "DEVICE_UP":
		err := d.ParseDeviceUpData()
		if err != nil {
			return err
		}
	case "DEVICE_CONTROL":
		err := d.ParseDeviceControlData()
		if err != nil {
			return err
		}
		logrus.Info("DEVICE_CONTROL")
	case "SPK_CTRL_T1":
		err := d.ParseSpkCtrlT1Data()
		if err != nil {
			return err
		}
		logrus.Info("SPK_CTRL_T1")
	case "SPK_CTRL_T2":
		err := d.ParseSpkCtrlT2Data()
		if err != nil {
			return err
		}
		logrus.Info("SPK_CTRL_T2")
	case "FAN_CTRL_T":
		err := d.ParseFanCtrlTData()
		if err != nil {
			return err
		}
		logrus.Info("FAN_CTRL_T")
	case "LIGHT_CTRL_T":
		err := d.ParseLightCtrlTData()
		if err != nil {
			return err
		}
		logrus.Info("LIGHT_CTRL_T")
	case "MIST_CTRL_T":
		err := d.ParseMistCtrlTData()
		if err != nil {
			return err
		}
		logrus.Info("MIST_CTRL_T")
	case "PUMP_CTRL_T":
		err := d.ParsePumpCtrlTData()
		if err != nil {
			return err
		}
		logrus.Info("PUMP_CTRL_T")
	default:
		logrus.Warn("未知的包类型")
	}
	return nil
}
